<template>
  <div class="post-detail">
    <el-card
        v-if="post"
        shadow="hover"
        style="max-width: 720px;
        margin: 40px auto;
        padding: 20px;"
    >
      <el-row justify="space-between" align="middle" style="margin-bottom: 20px;">
        <el-col>
          <h1 style="margin: 0; text-align: center">{{ post.title }}</h1>
        </el-col>
        <el-col style="text-align: right;">
          <div style="display: flex; align-items: center; justify-content: flex-end; gap: 12px; color: #666; font-weight: 600;">
            <span>作者: {{ post.nickname || '匿名' }}</span>

<!--            <el-dropdown>-->
<!--            <span class="el-dropdown-link" style="cursor: pointer; color: #409EFF;">-->
<!--              编辑-->
<!--              <el-icon class="el-icon&#45;&#45;right">-->
<!--                <arrow-down />-->
<!--              </el-icon>-->
<!--            </span>-->
<!--              <template #dropdown>-->
<!--                <el-dropdown-menu>-->
<!--                  <el-dropdown-item @click="goEdit">修改</el-dropdown-item>-->
<!--                  <el-dropdown-item @click="deletePost">删除</el-dropdown-item>-->
<!--                </el-dropdown-menu>-->
<!--              </template>-->
<!--            </el-dropdown>-->
            <el-dropdown v-if="canEdit">
              <span class="el-dropdown-link" style="cursor: pointer; color: #409EFF;">
                编辑
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="goEdit">修改</el-dropdown-item>
                  <el-dropdown-item @click="deletePost">删除</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

          </div>
        </el-col>

      </el-row>

      <div v-html="post.content"></div>

      <p style="color: #999; font-size: 12px; text-align: right; margin-top: 40px;">
        发布时间: {{ formatDate(post.createdAt) }}
      </p>

      <div class="comments-section">
        <h3>评论</h3>

        <div v-if="!currentUserId" class="login-tip">
          <el-alert title="请先登录后评论" type="warning" show-icon />
        </div>

        <div v-else class="comment-form">
          <el-input
              type="textarea"
              v-model="newComment"
              placeholder="说点什么吧..."
              :rows="3"
              maxlength="500"
              show-word-limit
          ></el-input>

          <el-button
              type="primary"
              style="margin-top: 10px;"
              @click="submitComment"
          >
            发布评论
          </el-button>
        </div>

        <div v-if="comments.length" class="comment-list" style="margin-top: 20px;">
          <div
              v-for="comment in comments"
              :key="comment.id"
              class="comment-item"
              style="border-bottom: 1px solid #eee; padding: 10px 0;"
          >
            <el-row justify="space-between" align="middle">
              <el-col>
                <strong>{{ comment.nickname || '匿名' }}</strong>
              </el-col>
              <el-col style="color: #999; font-size: 12px;">
                {{ formatDate(comment.createdAt) }}
              </el-col>
            </el-row>
            <p style="margin-top: 5px;">{{ comment.content }}</p>
          </div>
        </div>

        <div v-else style="margin-top: 20px; color: #999;">暂无评论</div>
      </div>
      <el-row>
        <el-col style="text-align: center;">
          <el-button style="margin-top: 10px" type="primary" @click="goBack">返回文章</el-button>
        </el-col>
      </el-row>
    </el-card>
    <div v-else style="text-align: center; margin-top: 50px;">
      正在加载文章内容...
    </div>
  </div>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue';
import {useRoute, useRouter} from 'vue-router';
import axios from 'axios';
import {ElMessage, ElMessageBox} from 'element-plus';
import {addComment, getCommentsByPostId} from '@/api/comment.js';
import {ArrowDown} from '@element-plus/icons-vue';
import { usePostStore } from '@/stores/postStore';

const route = useRoute();
const router = useRouter();
const postStore = usePostStore();

const postId = computed(() => route.params.id);  // 先定义
const post = ref(null); // 避免提前用 .value 报错

const comments = ref([]);
const newComment = ref('');

const currentUserId = localStorage.getItem('userId');
const currentNickname = localStorage.getItem('nickname');

function applyCachedNickname(postObj) {
  if (postObj?.userId) {
    const cached = localStorage.getItem(`author_${postObj.userId}`);
    if (cached) {
      postObj.nickname = cached;
    }
  }
}


const formatDate = (dateStr) => {
  const date = new Date(dateStr);
  return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
};

// const fetchPost = async () => {
//   try {
//     const res = await axios.get(`/api/posts/${postId.value}`);
//     post.value = res.data;
//     console.log(post.value);
//   } catch (error) {
//     ElMessage.error('获取文章失败');
//   }
// };
const fetchPost = async () => {
  try {
    const res = await axios.get(`/api/posts/${postId.value}`);
    const data = res.data;
    applyCachedNickname(data); // 👈 补充作者昵称
    post.value = data;
  } catch (error) {
    ElMessage.error('获取文章失败');
  }
};


const fetchComments = async () => {
  try {
    const res = await getCommentsByPostId(postId.value);
    comments.value = res.data;
  } catch (error) {
    ElMessage.error('获取评论失败');
  }
};

const canEdit = computed(() => {
  return post.value?.userId && currentUserId && post.value.userId.toString() === currentUserId.toString();
});

const goBack = () => {
  //router.back();
  router.push('/home');
};

const goEdit = () => {
  router.push(`/edit-post/${post.value.id}`);
};

const deletePost = () => {
  ElMessageBox.confirm(
      '确定要删除这篇文章吗？此操作无法撤销。',
      '删除确认',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(async () => {
    try {
      await axios.delete(`/api/posts/${post.value.id}`);
      ElMessage.success('删除成功');
      await router.push('/');
    } catch (error) {
      ElMessage.error('删除失败');
    }
  }).catch(() => {});
};

const submitComment = async () => {
  if (!newComment.value.trim()) {
    ElMessage.warning('请输入评论内容');
    return;
  }

  const newCommentData = {
    postId: postId.value,
    userId: currentUserId,
    content: newComment.value,
    nickname: currentNickname,
  };

  try {
    const res = await addComment(newCommentData);
    if (res.data === 'success') {
      ElMessage.success('评论成功！');
      newComment.value = '';
      await fetchComments();
    } else {
      ElMessage.warning('评论失败');
    }
  } catch (error) {
    ElMessage.error('评论失败');
  }
};

// onMounted(() => {
//   const cachedPost = postStore.getPostById(postId.value);
//   if (cachedPost) {
//     post.value = cachedPost;
//   } else {
//     fetchPost();
//   }
//   fetchComments();
// });
onMounted(() => {
  const cachedPost = postStore.getPostById(postId.value);
  if (cachedPost) {
    applyCachedNickname(cachedPost); // 👈 也补充一下
    post.value = cachedPost;
  } else {
    fetchPost();
  }
  fetchComments();
});

</script>



<style scoped>
.post-detail {
  max-width: 720px;
  margin: 40px auto;
  padding: 20px;
}

.action-buttons {
  margin-top: 20px;
  display: flex;
  gap: 12px;
  flex-wrap: wrap;
}

.comments-section {
  margin-top: 40px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.comment-form {
  margin-top: 10px;
}

.comment-list {
  margin-top: 20px;
}

.comment-item {
  border-bottom: 1px solid #eee;
  padding: 10px 0;
}

.comment-author {
  font-weight: bold;
}

.comment-content {
  margin: 5px 0;
}

.comment-date {
  color: #999;
  font-size: 12px;
}
</style>
